import { InjectQueue } from '@nestjs/bullmq';
import { Injectable } from '@nestjs/common';
import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import Util, * as $Util from '@alicloud/tea-util';
import Credential from '@alicloud/credentials';
import * as $tea from '@alicloud/tea-typescript';
import { Queue } from 'bullmq';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class SmsService {
  client: Dysmsapi20170525;
  sign: string;
  constructor(
    @InjectQueue('sms')
    private smsQueue: Queue,
    private configService: ConfigService,
  ) {
    this.initClient();
  }

  private initClient() {
    // 工程代码建议使用更安全的无AK方式，凭据配置方式请参见：https://help.aliyun.com/document_detail/378664.html。
    const credential = new Credential();
    const config = new $OpenApi.Config({
      credential: credential,
    });
    // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
    config.endpoint = `dysmsapi.aliyuncs.com`;
    this.client = new Dysmsapi20170525(config);
  }

  async pushCodeSmsQueue(phone: string, code: string) {
    const job = await this.smsQueue.add('code', {
      phone,
      template: '',
      params: {
        code,
      },
    });
    console.log(job.id);
  }

  // 单条短信
  async sendSms(phone: string, template: string, params: any) {
    const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: phone,
      signName: this.sign,
      templateCode: template,
      templateParam: JSON.stringify(params),
    });
    try {
      // 复制代码运行请自行打印 API 的返回值
      await this.client.sendSmsWithOptions(
        sendSmsRequest,
        new $Util.RuntimeOptions({}),
      );
    } catch (error) {
      // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
      // 错误 message
      console.log(error.message);
      // 诊断地址
      console.log(error.data['Recommend']);
    }
  }

  // 群发短信
  sendBatchSms(phones: string[]) {
    console.log(phones);
  }
}
